import React, {memo, useState, useEffect} from 'react'
import {
	Button,
	Space,
	Table,
	Popconfirm,
	message,
	TreeSelect,
	Row,
	Col,
	Form,
} from 'antd'
import type {ColumnsType} from 'antd/es/table'
import {ArrowDownOutlined} from '@ant-design/icons'
import {history, connect} from 'umi'
import {getTableData, deleteCompany, getCompany} from '@/service/system/company'
import {translateDataToTree} from '@/utils/common/index'
import styles from './index.less'
import Permissions from '@/components/Permissions'
import {downloadDocumentUrl} from '@/service/common/download'

interface DataType {
	adminList: any
	key: React.ReactNode
	name: string
	id: number
	parentId: number
	children?: DataType[]
}

const companyDom = memo((props: {dispatch: any; user: any}) => {
	const [form] = Form.useForm()
	const {currentMerchantId, orgId} = props.user
	const [loading, setLoading] = useState(false)
	const [orginDataSource, setOrginDataSource] = useState<any>()
	const [dataSource, setDataSource] = useState<any>()
	const [orgSource, setOrgSource] = useState<any>()
	const [merchantId, setMerchantId] = useState<any>('')
	const [defaultExpandAllRows, setDefaultExpandAllRows] = useState<any>(false)
	const [random, setRandom] = useState<any>()
	// 获取表格数据
	const onListFun = () => {
		if (merchantId) {
			setLoading(true)
			getTableData({merchantId})
				.then((res: any) => {
					if (res?.success) {
						setOrginDataSource(() => res?.data)
						const list = translateDataToTree(res?.data)
						const data = list?.map((item: any) => {
							if (item?.children) {
								item?.children?.map((i: any) => {
									const newItem = i
									if (newItem?.children) {
										delete newItem?.children
									}
									return newItem
								})
							}
							return item
						})
						setDefaultExpandAllRows(() => false)
						setDataSource(() => data)
					}
					setLoading(false)
				})
				.catch(() => {
					setLoading(false)
				})
		}
	}
	const searchTree = (tree: any, id: any, children: any) => {
		let state = false
		// eslint-disable-next-line no-shadow
		function readTree(tree: any, id: any) {
			if (state) return
			for (let i = 0; i < tree.length; i += 1) {
				if (tree[i].id === id) {
					state = true
					if (children.length > 0) {
						// eslint-disable-next-line no-param-reassign
						tree[i].children = children
					} else {
						// eslint-disable-next-line no-param-reassign
						delete tree[i].children
					}
				} else if (tree[i].children != null) {
					readTree(tree[i].children, id)
				}
			}
		}
		readTree(tree, id)
	}
	const onExpandFun = (expanded: any, record: any) => {
		const childrenList = orginDataSource?.filter(
			(item: any) => item.parentId === record.id,
		)
		const children = childrenList.map((item: any) => {
			const newItem = item
			const sunList = orginDataSource?.filter(
				(i: any) => i.parentId === newItem.id,
			)
			if (sunList.length > 0) {
				newItem.children = [...sunList]
			}
			return newItem
		})
		searchTree(dataSource, record?.id, children)
		setDataSource(() => dataSource)
	}

	// 获取组织机构数据
	const onOrgFun = () => {
		getCompany({merchantId: orgId}).then((res: any) => {
			if (res?.success) {
				const list: any = translateDataToTree(res?.data)
				setOrgSource(list as any)
				if (!currentMerchantId) {
					setMerchantId(() => list[0]?.id)
					form.setFieldsValue({merchantId: list[0]?.id})
				} else {
					setMerchantId(() => currentMerchantId)
					form.setFieldsValue({merchantId: currentMerchantId})
				}
			}
		})
	}
	useEffect(() => {
		onOrgFun()
	}, [currentMerchantId])

	useEffect(() => {
		// 初始化表格
		onListFun()
	}, [merchantId])

	// 编辑事件
	const onEditFun = (id: any) => {
		history.push({
			pathname: '/system/company/edit',
			query: {
				id,
			},
		})
	}

	const getRandom = () => {
		const r = Math.random() * (20 - 10) + 10000
		setRandom(() => r)
	}
	useEffect(() => {
		getRandom()
	}, [merchantId, orginDataSource])
	// 删除事件
	const onDeleteFun = (id: any) => {
		deleteCompany(id)
			.then((res: any) => {
				if (res.success) {
					message.success(res.msg)
					getRandom()
					onListFun()
				}
			})
			.catch((err) => {
				message.success(err)
			})
	}

	// 分享事件
	const onShareFun = (id: any) => {
		const data = form.getFieldsValue()
		history.push({
			pathname: '/system/company/share',
			query: {
				id,
				merchantId: data.merchantId,
			},
		})
	}

	// 查看事件
	const onViewFun = (id: any) => {
		history.push({
			pathname: '/system/company/view',
			query: {
				id,
			},
		})
	}
	const columns: ColumnsType<DataType> = [
		{
			title: '公司组织',
			dataIndex: 'name',
			key: 'name',
			ellipsis: true,
			render: (text) => <div className="ellipsis">{text || '--'}</div>,
		},
		{
			title: '管理员',
			dataIndex: 'adminList',
			key: 'adminList',
			align: 'center',
			ellipsis: true,
			render: (text: any, row: any) => {
				const adminList = row?.adminList.map(
					(item: {name: string}) => item.name,
				)
				return (
					<>
						{adminList.length ? (
							<div
								title={
									adminList.length
										? adminList?.join(',')
										: '--'
								}>
								{adminList.length > 3
									? `${adminList
											?.slice(0, 3)
											?.join(',')} . . .`
									: adminList?.join(',')}
							</div>
						) : (
							'--'
						)}
					</>
				)
			},
		},
		{
			title: '备注',
			dataIndex: 'description',
			key: 'description',
			align: 'center',
			ellipsis: true,
			render: (text) => <div className="ellipsis">{text || '--'}</div>,
		},
		{
			title: '操作',
			dataIndex: 'option',
			width: 300,
			key: 'option',
			align: 'center',
			render: (text: any, record: any) => (
				<div>
					<Permissions permissionID="amc_system_permission_company_add">
						<Button
							type="link"
							size="small"
							onClick={() => {
								history.push({
									pathname: '/system/company/add',
									query: {
										cid: record?.id,
									},
								})
							}}>
							新增
						</Button>
					</Permissions>
					{record.parentId === 0 ? (
						''
					) : (
						<Permissions permissionID="amc_system_permission_company_edit">
							<Button
								type="link"
								size="small"
								onClick={() => onEditFun(record.id)}>
								修改
							</Button>
						</Permissions>
					)}
					<Permissions permissionID="amc_system_permission_company_view">
						<Button
							type="link"
							size="small"
							onClick={() => onViewFun(record.id)}>
							查看
						</Button>
					</Permissions>
					{record.parentId === 0 ? (
						''
					) : (
						<Permissions permissionID="amc_system_permission_company_share">
							<Button
								type="link"
								size="small"
								onClick={() => onShareFun(record.id)}>
								分配城市
							</Button>
						</Permissions>
					)}
					{record.parentId === 0 ? (
						''
					) : (
						<Permissions permissionID="amc_system_permission_company_delete">
							<Popconfirm
								placement="topLeft"
								title="你确定要删除该公司组织？"
								onConfirm={() => onDeleteFun(record.id)}
								okText="确定"
								cancelText="取消">
								<Button type="link" size="small">
									删除
								</Button>
							</Popconfirm>
						</Permissions>
					)}
				</div>
			),
		},
	]

	const onChange = (key: string | string[]) => {
		setMerchantId(() => key)
		props.dispatch({
			type: 'user/updateCurrentMerchantId',
			payload: {
				currentMerchantId: key,
			},
		})
	}

	return (
		<div className={styles.content}>
			<div className="searchForm">
				<Form
					name="basic"
					form={form}
					layout="horizontal"
					labelCol={{flex: '80px'}}
					initialValues={{remember: true}}
					autoComplete="off">
					<Row gutter={12}>
						<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
							<Form.Item
								label="组织机构"
								name="merchantId"
								rules={[{required: true}]}>
								<TreeSelect
									showSearch
									treeNodeFilterProp="name"
									style={{width: '100%'}}
									dropdownStyle={{
										maxHeight: 400,
										overflow: 'auto',
									}}
									placeholder="请输入组织机构"
									treeDefaultExpandAll
									onChange={onChange}
									fieldNames={{
										label: 'name',
										value: 'id',
									}}
									treeData={orgSource}
								/>
							</Form.Item>
						</Col>
					</Row>
				</Form>
			</div>
			<div className="btnlist">
				<Space size={12}>
					<Button
						icon={<ArrowDownOutlined />}
						type="primary"
						ghost
						size="small"
						onClick={() =>
							downloadDocumentUrl({
								resourceId: '94',
								queryDesc: '公司导出,merchantId:公司Id',
								queryParam: {
									merchantId,
								},
							})
						}>
						导出
					</Button>
				</Space>
			</div>
			<>
				<Table
					key={random}
					rowKey={(record) => record.id}
					columns={columns}
					dataSource={dataSource}
					bordered
					defaultExpandAllRows={defaultExpandAllRows}
					onExpand={onExpandFun}
					loading={loading}
					pagination={false}
				/>
			</>
		</div>
	)
})
export default connect(({user}: any) => ({user}))(companyDom)
